package com.coocaa.ops.api.v1.internal.service;

import com.coocaa.ops.api.v1.internal.provider.ICacheUpdateProvider;
import com.coocaa.ops.common.tool.base.InstanceUtil;
import com.coocaa.ops.common.tool.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Map;

/**
 * @author bijiahao
 * @date : 2019/6/20.
 * @description 缓存更新服务接口实现
 *
 */
@Service
@Slf4j
public class CacheUpdateMgrServiceImpl implements ICacheUpdateMgrService {
    /**
     * 各业务的ICacheUpdateProvider实现类会自动注入到该map，key为bean名称
     */
    @Autowired
    private Map<String, ICacheUpdateProvider> cacheUpdateProviderMap;

    @Override
    public List<String> updateCacheByResourceIdAndType(String id, String type) {
        Integer resourceId = null;
        try {
            List<String> keys = getCacheUpdateProvider(type).updateCacheByResourceId(id);
            handleLog(keys);
            return keys;
        } catch (NumberFormatException e) {
            Map<String, Object> map = InstanceUtil.newHashMap(2);
            map.put("id", id);
            map.put("type", type);
            throw new BusinessException(map, "解析资源ID异常！");
        }
    }

    /*************** ===私有方法=== ********************* ===start=== ***************************************/

    /**
     * 获取 对应资源类别的缓存更新-提供者实例
     *
     * @param type
     * @return
     */
    private ICacheUpdateProvider getCacheUpdateProvider(String type) {
        ICacheUpdateProvider cacheUpdateProvider = cacheUpdateProviderMap.get(type);
        Assert.notNull(cacheUpdateProvider, "该资源类别对应的ICacheUpdateProvider更新缓存实例不能为空,type: " + type);
        return cacheUpdateProvider;
    }

    private void handleLog(List<String> keys) {
        if (CollectionUtils.isEmpty(keys)) {
            return;
        }

        StringBuilder b = new StringBuilder("\n缓存更新：\n");
        for (String key : keys) {
            b.append(key).append("\n");
        }
        log.info(b.toString());
    }
}
